package org.javaboy.security_role_permission.model;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class User implements UserDetails {
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", enabled=" + enabled +
                ", roles=" + roles +
                ", permissions=" + permissions +
                '}';
    }

    private Integer id;
    private String username;
    private String password;
    private Boolean enabled;

    private List<Role> roles;
    private List<Permission> permissions;

    public User() {
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }

    /**
     * 获取权限
     * Role Permission
     * <p>
     * 在 Spring Security 中，用户对象中只存在 getAuthorities。无论用户是具备角色 还是具备权限，
     * 在 Spring Security 中都是以 GrantedAuthority 的形式存在。
     * 如果一定要区分，那么角色是以 ROLE_ 开始的，而权限则没有限制。
     * <p>
     * 一般建议就在这里返回权限，如果需要返回角色，技术上也是没问题的，但是不建议这么做。
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> rolesList = roles.stream().map(r -> new SimpleGrantedAuthority(r.getName())).collect(Collectors.toList());
        List<SimpleGrantedAuthority> permList = permissions.stream().map(p -> new SimpleGrantedAuthority(p.getPname())).collect(Collectors.toList());
        permList.addAll(rolesList);
        return permList;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}
